const mongoose = require('mongoose');
require('dotenv').config();

/**
 * 连接数据库
 * @returns {Promise<mongoose.Connection>} 数据库连接
 */
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGODB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    console.log(`MongoDB 连接成功: ${conn.connection.host}`);
    return conn;
  } catch (error) {
    console.error(`MongoDB 连接错误: ${error.message}`);
    process.exit(1);
  }
};

/**
 * 清理数据库中的孤立数据
 * @returns {Promise<Object>} 清理结果统计
 */
const cleanupOrphanData = async () => {
  try {
    const Document = require('../models/Document');
    const Card = require('../models/Card');
    const Exercise = require('../models/Exercise');
    const LearningPath = require('../models/LearningPath');
    const UserLearningProgress = require('../models/UserLearningProgress');
    const User = require('../models/User');
    const fileUpload = require('./fileUpload');
    
    const result = {
      cards: 0,
      exercises: 0,
      learningPaths: 0,
      progressRecords: 0,
      orphanedFiles: 0
    };
    
    console.log('开始清理数据库中的孤立数据...');
    
    // 1. 查找所有文档ID
    const documents = await Document.find({}, '_id');
    const documentIds = documents.map(doc => doc._id.toString());
    
    // 2. 查找所有用户ID
    const users = await User.find({}, '_id');
    const userIds = users.map(user => user._id.toString());
    
    // 3. 删除孤立的卡片（没有对应的文档）
    const cardDeleteResult = await Card.deleteMany({
      $or: [
        { sourceDocument: { $nin: documentIds } },
        { sourceDocument: { $exists: false } }
      ]
    });
    result.cards = cardDeleteResult.deletedCount;
    console.log(`删除了 ${cardDeleteResult.deletedCount} 张孤立的卡片`);
    
    // 4. 删除孤立的练习题（没有对应的用户）
    const exerciseDeleteResult = await Exercise.deleteMany({
      $or: [
        { createdBy: { $nin: userIds } },
        { createdBy: { $exists: false } }
      ]
    });
    result.exercises = exerciseDeleteResult.deletedCount;
    console.log(`删除了 ${exerciseDeleteResult.deletedCount} 个孤立的练习题`);
    
    // 5. 查找所有学习路径ID
    const learningPaths = await LearningPath.find({}, '_id');
    const learningPathIds = learningPaths.map(path => path._id.toString());
    
    // 6. 删除孤立的学习路径（没有对应的文档或用户）
    const pathDeleteResult = await LearningPath.deleteMany({
      $or: [
        { documentId: { $nin: documentIds } },
        { documentId: { $exists: false } },
        { createdBy: { $nin: userIds } }
      ]
    });
    result.learningPaths = pathDeleteResult.deletedCount;
    console.log(`删除了 ${pathDeleteResult.deletedCount} 个孤立的学习路径`);
    
    // 7. 删除孤立的学习进度（没有对应的用户或学习路径）
    const progressDeleteResult = await UserLearningProgress.deleteMany({
      $or: [
        { userId: { $nin: userIds } },
        { userId: { $exists: false } },
        { learningPathId: { $nin: learningPathIds } },
        { learningPathId: { $exists: false } }
      ]
    });
    result.progressRecords = progressDeleteResult.deletedCount;
    console.log(`删除了 ${progressDeleteResult.deletedCount} 条孤立的学习进度记录`);
    
    // 8. 清理孤立的物理文件
    const orphanedFilesResult = await fileUpload.cleanupOrphanedFiles();
    result.orphanedFiles = orphanedFilesResult.deleted;
    console.log(`删除了 ${orphanedFilesResult.deleted} 个孤立的物理文件`);
    
    console.log('数据库清理完成');
    return result;
  } catch (error) {
    console.error('清理数据库时出错:', error);
    throw error;
  }
};

// 导出函数
const db = {
  connect: connectDB,
  cleanupOrphanData
};

module.exports = db; 